<template>
  <div>
    <el-dialog
      title="分配角色"
      :visible="roleShow"
      width="50%"
      @close="roleDialogClose"
    >
      <div>
        当前的用户: <span>{{ role.username }}</span>
      </div>
      <div class="curr">
        当前的角色： <span>{{ role.role_name }}</span>
      </div>
      <div>
        分配新角色：
        <el-select v-model="value" placeholder="请选择">
          <el-option
            v-for="item in newRoles"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          />
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="$emit('input',false)">取 消</el-button>
        <el-button type="primary" @click="userRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getRole } from '@/api/role.js'
import { allotUser } from '@/api/user.js'

export default {
  model: {
    prop: 'roleShow'
  },
  props: {
    roleShow: {
      type: Boolean,
      required: true
    },
    role: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      newRoles: [],
      value: ''
    }
  },

  created() {
    this.loadRole()
  },

  methods: {
    // 关闭弹层
    roleDialogClose() {
      this.$emit('input', false)
    },
    async loadRole() {
      // 拿到角色列表
      const res = await getRole()
      this.newRoles = res
    },
    // 点击确认分配角色
    async userRole() {
      try {
        await allotUser(this.role.id, this.value)
        this.$message.success('分配成功')
        this.roleDialogClose()
        this.$emit('loadUser')
      } catch (err) {
        console.log(err)
      }
    }
  }
}
</script>

<style scoped lang='scss'>
.curr {
  padding: 10px 0;
}

</style>
